import csv
import json
import uuid
import os
import subprocess
from datetime import datetime

from get_project_path import project_path


def parse_jtl_to_allure(jtl_path, allure_results_dir=f'{project_path}/report/tmp'):
    """解析JTL文件并生成Allure结果文件"""
    os.makedirs(allure_results_dir, exist_ok=True)
    def detect_delimiter(file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            sample = f.read(1024)
        delimiters = [',', ';', '\t', '|']
        for delimiter in delimiters:
            if delimiter in sample:
                return delimiter
        return ','  # 默认

    delimiter = detect_delimiter(jtl_path)
    with open(jtl_path, 'r', encoding='utf-8', errors='replace') as file:
        # 检测JTL文件是CSV还是XML格式
        # sniffer = csv.Sniffer()
        # dialect = sniffer.sniff(file.read(1024))
        # file.seek(0)
        is_csv = True
        # try:
        #     csv_reader = csv.DictReader(file, dialect=dialect)
        #     fieldnames = csv_reader.fieldnames
        # except:
        #     is_csv = False

        if is_csv:
            lines = [line for line in file if not line.strip().startswith('#')]
            csv_reader = csv.DictReader(lines, delimiter=delimiter)
            csv_reader.fieldnames = [name.strip() for name in csv_reader.fieldnames]
            # 处理CSV格式
            for row in csv_reader:
                # 转换字段
                test_case = {
                    'name': row.get('label', 'Unnamed Test'),
                    'status': 'passed' if row.get('success', 'true').lower() == 'true' else 'failed',
                    'start': int(row.get('timeStamp', 0)),
                    'stop': int(row.get('timeStamp', 0)) + int(row.get('elapsed', 0)),
                    'parameters': [
                        {'name': key, 'value': str(value)}
                        for key, value in row.items() if key not in ['label', 'success']
                    ],
                    'uuid': str(uuid.uuid4()),
                    'historyId': row.get('label', '') + '_' + row.get('responseCode', ''),
                    'fullName': row.get('label', 'Unnamed Test'),
                    'labels': [
                        {'name': 'suite', 'value': 'JMeter Tests'},
                        {'name': 'tag', 'value': 'performance'}
                    ]
                }
                # 保存为JSON文件
                with open(f'{allure_results_dir}/{test_case["uuid"]}-result.json', 'w') as json_file:
                    json.dump(test_case, json_file)
        else:
            # 处理XML格式（需要根据实际结构调整）
            import xml.etree.ElementTree as ET
            tree = ET.parse(file)
            root = tree.getroot()
            for sample in root.findall('.//sample'):
                # 示例解析，需根据实际XML结构调整
                test_case = {
                    'name': sample.get('lb', 'Unnamed Test'),
                    'status': 'passed' if sample.get('s', 'true') == 'true' else 'failed',
                    'start': int(sample.get('ts', 0)),
                    'stop': int(sample.get('ts', 0)) + int(sample.get('t', 0)),
                    'uuid': str(uuid.uuid4()),
                    'parameters': [
                        {'name': 'responseCode', 'value': sample.get('rc', '')},
                        {'name': 'responseMessage', 'value': sample.get('rm', '')}
                    ]
                }
                with open(f'{allure_results_dir}/{test_case["uuid"]}-result.json', 'w') as json_file:
                    json.dump(test_case, json_file)


def generate_allure_report(allure_results_dir=rf'D:\Github\netflow_ui\report\tmp', report_dir=rf'D:\Github\netflow_ui\repor\html'):
    """生成Allure HTML报告"""
    # subprocess.run(['allure', 'generate', allure_results_dir, '-o', report_dir, '--clean'], check=True)
    os.system(r"allure generate ./report/tmp -o ./report/html --clean")
    print(f"Allure report generated at: {os.path.abspath(report_dir)}")


if __name__ == '__main__':
    jtl_file = r'D:\Tools\apache-jmeter-5.6.3\bin\result2.jtl'  # 修改为你的JTL文件路径
    parse_jtl_to_allure(jtl_file)
    generate_allure_report()